import React, {useEffect, useState, useRef} from 'react';
import {
  ScrollView,
  StatusBar,
  StyleSheet,
  Text,
  useColorScheme,
  View,
  Button,
  FlatList,
  Dimensions,
  Image,
  TouchableOpacity,
} from 'react-native';
import CategoryModal, {CategoryModalRef} from './CategoryModal';
import icon_arrow from '../../../assets/icon_arrow.png';

type Props = {
  categoryList: Category[];
  allCategoryList: Category[];
  onCategoryChange: (category: Category) => void;
};

export default ({categoryList, allCategoryList, onCategoryChange}: Props) => {
  const modalRef = useRef<CategoryModalRef>(null);
  const onCategoryPress = (category: Category) => {
    // 当类别改变时调用onCategoryChange函数，传入参数category
    setCategory(category);
    onCategoryChange?.(category);
  };
  // 声明一个变量category，用于存储选中Category类型的值
  const [category, setCategory] = useState<Category>();
  // 使用useEffect来设置category的初始值
  useEffect(() => {
    // 设置category的初始值为categoryList中name为'推荐'的值
    setCategory(categoryList.find(i => i.name === '推荐'));
  }, []);

  const styles = StyleSheet.create({
    container: {
      width: '100%',
      height: 36,
      flexDirection: 'row',
      backgroundColor: 'white',
      marginBottom: 6,
    },
    scrollView: {
      flex: 1,
      height: '100%',
    },
    openButton: {
      width: 40,
      height: '100%',
      justifyContent: 'center',
      alignItems: 'center',
    },
    openImg: {
      width: 18,
      height: 18,
      transform: [{rotate: '-90deg'}],
    },
    tabItem: {
      width: 64,
      height: '100%',
      justifyContent: 'center',
      alignItems: 'center',
    },
    tabItemTxt: {
      fontSize: 16,
      color: '#999',
    },
    tabItemTxtSelected: {
      fontSize: 16,
      color: '#333',
      fontWeight: 'bold',
    },
  });

  return (
    <View style={styles.container}>
      <ScrollView
        style={styles.scrollView}
        horizontal={true}
        showsHorizontalScrollIndicator={false}>
        {categoryList.map((item: Category, index: number) => {
          // 设置当前项目是否被选中
          const isSelected = item.name === category?.name;
          return (
            <TouchableOpacity
              key={`${item.name}`}
              style={styles.tabItem}
              onPress={() => onCategoryPress(item)}>
              <Text
                style={
                  isSelected ? styles.tabItemTxtSelected : styles.tabItemTxt
                }>
                {item.name}
              </Text>
            </TouchableOpacity>
          );
        })}
      </ScrollView>
      <TouchableOpacity
        style={styles.openButton}
        onPress={() => {
          console.log('进来打印2024');

          modalRef.current?.show();
        }}>
        <Image source={icon_arrow} style={styles.openImg}></Image>
      </TouchableOpacity>
      <CategoryModal ref={modalRef} categoryList={allCategoryList} />
    </View>
  );
};
